# -*- coding: utf-8 -*-
from configobj import ConfigObj
from Conf import INI_DIR,ROOT

_py = "Comps/Ini.py"

'''
INI配置文件管理模块
负责读取和写入ini配置文件
* version 1.4.12
'''


class Ini:
    def __init__(self):
        self.py = _py
        self.ini_dir = None
        self.da = None

    def run(self):
        self.ini_dir = ROOT + INI_DIR
        print(self.ini_dir)
        self.da = ConfigObj(self.ini_dir, encoding='UTF8')

    def get(self, not_in=()):
        da = {}
        for section in self.da:
            if section in not_in:
                continue
            items = self.get_section(section)
            da[section] = items
        return da

    def add(self, section, items):
        self.add_section(section, items)

    def get_section(self, section):
        da = {}
        if section in self.da:
            for key, val in self.da[section].items():
                da[key] = val
        else:
            return None
        return da

    # section必须要存在
    def set_section(self, section, items):
        try:
            self.da.reload()
        except Exception as err:
            pass
        if section in self.da:
            for key, val in items.items():
                self.da[section][key] = val
            self.da.write()

    # key如果不存在，则不会新增
    def update_section(self, section, items):
        try:
            self.da.reload()
        except Exception as err:
            pass
        if section in self.da:
            for key, val in items.items():
                if key in self.da[section]:
                    self.da[section][key] = val
            self.da.write()

    # 直接添加
    def add_section(self, section, items):
        try:
            self.da.reload()
        except Exception as err:
            pass
        self.da[section] = items
        self.da.write()

    def del_section(self, section):
        try:
            self.da.reload()
        except Exception as err:
            pass
        if section in self.da:
            self.da.pop(section)
            self.da.write()

    def get_val(self, section, key):
        if section in self.da:
            if key in self.da[section]:
                return self.da[section][key]
        return None

    # key值必须要存在
    def set_val(self, section, key, val):
        try:
            self.da.reload()
        except Exception as err:
            pass
        if section in self.da:
            if key in self.da[section]:
                self.da[section][key] = val
                self.da.write()

    def del_val(self, section, key):
        try:
            self.da.reload()
        except Exception as err:
            pass
        if section in self.da:
            if key in self.da[section]:
                self.da[section].pop(key)
                self.da.write()

    def write(self, da):
        self.da = da
        self.da.write()

    def get_da(self):
        try:
            self.da.reload()
        except Exception as err:
            pass
        return self.da
